package com.lekang.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestParam;
import com.lekang.common.annotation.Log;
import com.lekang.common.core.controller.BaseController;
import com.lekang.common.core.domain.AjaxResult;
import com.lekang.common.enums.BusinessType;
import com.lekang.system.domain.CheckInManagement;
import com.lekang.system.domain.Contract;
import com.lekang.system.domain.dto.CheckInWorkflowDTO;
import com.lekang.system.service.IContractService;
import com.lekang.system.service.ICheckInManagementService;
import com.lekang.common.utils.poi.ExcelUtil;
import com.lekang.common.core.page.TableDataInfo;

/**
 * 入住管理Controller
 * 
 * @author 刘卓
 * @date 2025-10-13
 */
@RestController
@RequestMapping("/system/management")
public class CheckInManagementController extends BaseController
{
    @Autowired
    private ICheckInManagementService checkInManagementService;
    @Autowired
    private IContractService contractService;

    /**
     * 查询入住管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:management:list')")
    @GetMapping("/list")
    public TableDataInfo list(CheckInManagement checkInManagement)
    {
        startPage();
        List<CheckInManagement> list = checkInManagementService.selectCheckInManagementList(checkInManagement);
        return getDataTable(list);
    }

    /**
     * 导出入住管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:management:export')")
    @Log(title = "入住管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CheckInManagement checkInManagement)
    {
        List<CheckInManagement> list = checkInManagementService.selectCheckInManagementList(checkInManagement);
        ExcelUtil<CheckInManagement> util = new ExcelUtil<CheckInManagement>(CheckInManagement.class);
        util.exportExcel(response, list, "入住管理数据");
    }

    /**
     * 获取入住管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:management:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(checkInManagementService.selectCheckInManagementById(id));
    }

    /**
     * 新增入住管理
     */
    @PreAuthorize("@ss.hasPermi('system:management:add')")
    @Log(title = "入住管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CheckInManagement checkInManagement)
    {
        return toAjax(checkInManagementService.insertCheckInManagement(checkInManagement));
    }

    /**
     * 第一步：提交申请/基本信息与资料
     */
    @PreAuthorize("@ss.hasPermi('system:management:add')")
    @Log(title = "入住管理-申请", businessType = BusinessType.INSERT)
    @PostMapping("/apply")
    public AjaxResult apply(@RequestBody CheckInWorkflowDTO dto) {
        // 若已有elderlyId则跳过新增
        com.lekang.system.domain.Elderly elderly = new com.lekang.system.domain.Elderly();
        elderly.setId(dto.elderlyId);
        elderly.setName(dto.name);
        elderly.setIdCard(dto.idCard);
        elderly.setContact(dto.contact);
        elderly.setAddress(dto.address);
        elderly.setPhoto(dto.photo);
        elderly.setIdCardFront(dto.idCardFront);
        elderly.setIdCardBack(dto.idCardBack);
        // 保存入住主记录（创建占位）
        CheckInManagement record = new CheckInManagement();
        record.setElderlyId(dto.elderlyId);
        record.setCheckInNo(dto.contractNo); // 暂用合同号或由前端生成
        checkInManagementService.insertCheckInManagement(record);
        return success(record);
    }

    /**
     * 第二步：保存评估草稿（JSON格式）
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-保存评估草稿", businessType = BusinessType.UPDATE)
    @PostMapping("/saveAssessmentDraft")
    public AjaxResult saveAssessmentDraft(@RequestParam Long checkInManagementId, 
                                          @RequestBody String assessmentDraftJson) {
        System.out.println("=== 保存评估草稿 DEBUG ===");
        System.out.println("checkInManagementId: " + checkInManagementId);
        System.out.println("assessmentDraftJson 长度: " + (assessmentDraftJson != null ? assessmentDraftJson.length() : "null"));
        System.out.println("assessmentDraftJson 内容预览: " + 
            (assessmentDraftJson != null && assessmentDraftJson.length() > 100 ? 
                assessmentDraftJson.substring(0, 100) + "..." : 
                assessmentDraftJson));
        
        CheckInManagement record = new CheckInManagement();
        record.setId(checkInManagementId);
        record.setAssessmentDraftJson(assessmentDraftJson);
        
        int result = checkInManagementService.updateCheckInManagement(record);
        System.out.println("更新结果: " + (result > 0 ? "成功" : "失败"));
        
        return toAjax(result);
    }
    
    /**
     * 第二步：获取评估草稿
     */
    @PreAuthorize("@ss.hasPermi('system:management:query')")
    @GetMapping("/getAssessmentDraft/{checkInManagementId}")
    public AjaxResult getAssessmentDraft(@PathVariable Long checkInManagementId) {
        System.out.println("=== 获取评估草稿 DEBUG ===");
        System.out.println("请求参数 checkInManagementId: " + checkInManagementId);
        
        CheckInManagement record = checkInManagementService.selectCheckInManagementById(checkInManagementId);
        
        System.out.println("查询到的记录: " + (record != null ? "存在" : "null"));
        if (record != null) {
            System.out.println("记录ID: " + record.getId());
            System.out.println("assessmentDraftJson 字段值: " + record.getAssessmentDraftJson());
            System.out.println("assessmentDraftJson 是否为null: " + (record.getAssessmentDraftJson() == null));
            if (record.getAssessmentDraftJson() != null) {
                System.out.println("assessmentDraftJson 长度: " + record.getAssessmentDraftJson().length());
                System.out.println("assessmentDraftJson 内容预览: " + 
                    (record.getAssessmentDraftJson().length() > 100 ? 
                        record.getAssessmentDraftJson().substring(0, 100) + "..." : 
                        record.getAssessmentDraftJson()));
            }
        }
        
        if (record != null && record.getAssessmentDraftJson() != null) {
            System.out.println("✅ 返回评估草稿数据");
            return success(record.getAssessmentDraftJson());
        }
        
        System.out.println("⚠️ 返回 null（没有草稿数据）");
        return success(null);
    }
    
    /**
     * 第二步：提交评估结果（这里只保存护理等级ID占位）
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-评估", businessType = BusinessType.UPDATE)
    @PostMapping("/assess")
    public AjaxResult assess(@RequestParam Long checkInManagementId, @RequestParam Long nursingLevelId) {
        CheckInManagement record = new CheckInManagement();
        record.setId(checkInManagementId);
        record.setNursingLevelId(nursingLevelId);
        return toAjax(checkInManagementService.updateCheckInManagement(record));
    }

    /**
     * 第三步：审批结果（简单占位，前端已模拟，这里仅回写备注或状态字段可扩展）
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-审批", businessType = BusinessType.UPDATE)
    @PostMapping("/approve")
    public AjaxResult approve(@RequestParam Long checkInManagementId, @RequestParam String result) {
        // 可扩展审批状态字段；当前表暂无字段，先透传成功
        return success();
    }

    /**
     * 第四步：配置入住（床位与期限、费用）
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-配置", businessType = BusinessType.UPDATE)
    @PostMapping("/configure")
    public AjaxResult configure(@RequestBody CheckInWorkflowDTO dto) {
        CheckInManagement record = new CheckInManagement();
        record.setId(dto.checkInManagementId);
        record.setBedId(dto.bedId);
        record.setCheckInStartTime(dto.checkInStartTime);
        record.setCheckInEndTime(dto.checkInEndTime);
        record.setDeposit(dto.deposit);
        record.setNursingFee(dto.nursingFee);
        record.setBedFee(dto.bedFee);
        record.setOtherFee(dto.otherFee);
        return toAjax(checkInManagementService.updateCheckInManagement(record));
    }

    /**
     * 第五步：签约并落合同
     */
    @PreAuthorize("@ss.hasPermi('system:contract:add')")
    @Log(title = "入住管理-签约", businessType = BusinessType.INSERT)
    @PostMapping("/sign")
    public AjaxResult sign(@RequestBody CheckInWorkflowDTO dto) {
        Contract contract = new Contract();
        contract.setContractNo(dto.contractNo);
        contract.setContractName(dto.contractName);
        contract.setStartDate(dto.contractStartDate);
        contract.setEndDate(dto.contractEndDate);
        contract.setSignTime(dto.signDate);
        contract.setPartyCName(dto.partyCName);
        contract.setPartyCPhone(dto.partyCPhone);
        contract.setContractFile(dto.contractFile);
        contract.setElderlyId(dto.elderlyId);
        contract.setCheckInManagementId(dto.checkInManagementId);
        return toAjax(contractService.insertContract(contract));
    }
    
    /**
     * 完整入住申请流程 - 一次性提交所有数据
     * 同时插入：老人表、入住管理表、家人表、合同表、床表
     */
    @PreAuthorize("@ss.hasPermi('system:management:add')")
    @Log(title = "入住管理-完整申请", businessType = BusinessType.INSERT)
    @PostMapping("/complete")
    public AjaxResult completeApplication(@RequestBody CheckInWorkflowDTO dto) {
        try {
            Long checkInManagementId = checkInManagementService.completeCheckInApplication(dto);
            if (checkInManagementId != null && checkInManagementId > 0) {
                return success("入住申请提交成功").put("id", checkInManagementId);
            } else {
                return error("入住申请提交失败");
            }
        } catch (Exception e) {
            return error("入住申请处理失败: " + e.getMessage());
        }
    }
    
    /**
     * 启动入住申请工作流
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-启动工作流", businessType = BusinessType.UPDATE)
    @PostMapping("/startWorkflow")
    public AjaxResult startWorkflow(@RequestParam Long checkInManagementId) {
        try {
            String processInstanceId = checkInManagementService.startCheckInWorkflow(checkInManagementId);
            return success("工作流启动成功").put("processInstanceId", processInstanceId);
        } catch (Exception e) {
            return error("工作流启动失败: " + e.getMessage());
        }
    }
    
    /**
     * 处理工作流任务
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理-处理任务", businessType = BusinessType.UPDATE)
    @PostMapping("/handleTask")
    public AjaxResult handleTask(@RequestParam String taskId, 
                                @RequestParam String opinion, 
                                @RequestParam Long auditStatus, 
                                @RequestParam Long checkInManagementId,
                                @RequestParam Long stepNo) {
        try {
            checkInManagementService.handleWorkflowTask(taskId, opinion, auditStatus, checkInManagementId, stepNo);
            return success("任务处理成功");
        } catch (Exception e) {
            return error("任务处理失败: " + e.getMessage());
        }
    }

    /**
     * 修改入住管理
     */
    @PreAuthorize("@ss.hasPermi('system:management:edit')")
    @Log(title = "入住管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CheckInManagement checkInManagement)
    {
        return toAjax(checkInManagementService.updateCheckInManagement(checkInManagement));
    }

    /**
     * 删除入住管理
     */
    @PreAuthorize("@ss.hasPermi('system:management:remove')")
    @Log(title = "入住管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(checkInManagementService.deleteCheckInManagementByIds(ids));
    }
}
